package cn.markjoy.springbootrabbit.config.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.IOException;
import java.util.Properties;

/**
 * @author zhaojiandong
 * @date 2018/8/31
 * @Description
 */
@Configuration
@EnableConfigurationProperties(MybatisProperties.class) //注册被`@ConfigurationProperties`注解的`bean`
@MapperScan("cn.markjoy.springbootrabbit.entity.mapper")
@EnableTransactionManagement
public class MybatisConfig
{
    @Autowired
    private MybatisProperties mybatisProperties;

    @Autowired
    private DruidDataSource druidDataSource;
    @Value(value = "${cn.markjoy.translation.enabled}")
    private String translationFlag;
    @Value(value = "${cn.markjoy.translation.except.path}")
    private String exceptPaths;

    @Value("$mybatis.typeAliasesPackage")
    private String typeAliasPackage;

    @Value("$mybatis.mapperLocations")
    private String mapperLocations;

    @Bean
    @Primary
    public SqlSessionFactoryBean produceSqlSessionFactoryBean() throws IOException
    {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();

        // 设置 `Mybatis` 映射文件位置
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(mybatisProperties.getMapperLocations()));

        // 设置领域对象的包名
        sqlSessionFactoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasPackage());

        // 设置数据源
        sqlSessionFactoryBean.setDataSource(druidDataSource);


        // 分页插件
        PageInterceptor pageHelper = new PageInterceptor();
        Properties props = new Properties();
        props.setProperty("reasonable", "true");
        props.setProperty("supportMethodsArguments", "true");
        props.setProperty("returnPageInfo", "check");
        props.setProperty("params", "count=countSql");
        pageHelper.setProperties(props);

        return sqlSessionFactoryBean;
    }

    @Bean
    @Primary
    public DataSourceTransactionManager dataSourceTransactionManager(DruidDataSource druidDataSource)
    {
        return new DataSourceTransactionManager(druidDataSource);
    }


}

